# -*- coding: utf-8 -*-

import urllib
import re
import json

from base import mcMovie
from base import mcSource

class cuevanaMovie(mcMovie):

	def __init__ (self, id=None):
		mcMovie.__init__(self, "cuevana", id)


	def loadInfo(self):

		self.url = "http://www.cuevana.tv/web/peliculas?&" + self.id + "&"
		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')
		#print salida

		#Cover
		rec_cover_url = re.compile('"img"><img src="([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.cover_url = match.group(1)

		#Title
		rec_title = re.compile('"tit">([^<]*)')
		match = re.search(rec_title, salida )
		if match != None:
			self.title = unicode(match.group(1).strip(), 'utf-8')


		#Original Title
		rec_original_title = re.compile('tulo original</h2>([^<]*)')
		match = re.search(rec_original_title, salida )
		if match != None:
			self.original_title = unicode(match.group(1).strip(), 'utf-8')


		#Idiomas
		rec_lang = re.compile('<b>Idioma:</b>([^<]*)')
		match = re.search(rec_lang, salida )
		if match != None:
			langs = []
			langs.append( self._getCodeFromName( match.group(1).strip() ) )

			self.languages = langs


		#Idiomas
		rec_sublang = re.compile('tulos:</b>([^<]*)')
		match = re.search(rec_sublang, salida )
		if match != None:
			langs = []
			langs.append( self._getCodeFromName( match.group(1).strip() ) )

			self.sub_languages = langs

		self.url = "http://www.cuevana.tv/#!/peliculas/"+ self.id +"/"

		#Parent Call
		mcMovie.loadInfo(self)


	def loadSources(self):

		url = "http://www.cuevana.tv/player/sources?id="+self.id+"&tipo=pelicula"
		salida = self._mcData.get( url )
		#salida = salida.replace('\n', ' ')
		#print salida

		str1 = "var sources ="
		pos = salida.find(str1)
		pos2 = salida.find("var label =")

		strjson = salida[pos+len(str1):pos2-len(", sel_source = 0; ")]
		result = json.loads(strjson)
		#print result
		for definition in result:
			for lang in result[definition]:
				for server in result[definition][lang]:
					s = mcSource()
					s.service = self.service
					s.id = self.id
					s.server = server
					s.definition = definition
					if int(definition) >= 720:
						s.is_hd = True
					
					s.audio_lang_id = lang
					s.audio_lang = self._getAudioLangFromId(lang)

					if not self.dbExistSource(server,definition, s.audio_lang):
						self._loadSourceUrl(s)
					self.sources.append(s)

		#Parent Call
		mcMovie.loadSources(self)


	def _loadSourceUrl(self, source):

		url = "http://www.cuevana.tv/player/source_get"

		data = {'def': source.definition,
			'audio': source.audio_lang_id,
			'host': source.server,
			'id': self.id,
			'tipo': 'pelicula',
			'wup_premium' : 'false'
			}

		post = urllib.urlencode(data)

		salida = self._mcData.post(url, post, 'sources_cookies')
		salida = salida.strip().replace('\xef\xbb\xbf', '')


		
		pos = salida.find('id="captcha"')
		
		if pos > 0:			
			#Captcha
			base_url = url + "?" + post
			
			while True:
			
				#Recaptcha here		
				result = self.reCaptcha('6LeO_MwSAAAAABVHhC7ftszdwEtjTpe-gId7KshJ', base_url , 'sources_cookies')
				if result.find('id="captcha"') < 0:
					break
							
				rec_surl = re.compile("http://go.cuevana.tv/\?([^']*)")
				match = re.search(rec_surl, result )
				if match != None:
					source.url = urllib.unquote_plus( match.group(1) )					
			
		else:	

			if source.server == 'megaupload':
				pos = salida.find('&id='+ self.id)
				salida = salida[:pos]

			if source.server == 'wupload':
				pos = salida.find('?id='+ self.id)
				salida = salida[:pos]

			source.url = salida				
	

	def _getAudioLangFromId(self, id):
		
		l = self.langs[str(id)]		
		return l['code']
	
	def _getCodeFromName(self, name):
		
		return self.langs_codes[str(name)]
		
	
	#{"1":"Espa\u00f1ol","2":"Ingl\u00e9s","3":"Portugu\u00e9s","4":"Alem\u00e1n","5":"Franc\u00e9s","6":"Coreano","7":"Italiano","8":"Tailand\u00e9s","9":"Ruso","10":"Mongol","11":"Polaco","12":"Esloveno","13":"Sueco","14":"Griego","15":"Canton\u00e9s","16":"Japon\u00e9s","17":"Dan\u00e9s","18":"Neerland\u00e9s","19":"Hebreo","20":"Serbio","21":"\u00c1rabe","22":"Hindi","23":"Noruego","24":"Turco","26":"Mandar\u00edn","27":"Nepal\u00e9s","28":"Rumano","29":"Iran\u00ed","30":"Est\u00f3n","31":"Bosnio","32":"Checo","33":"Croata","34":"Fin\u00e9s","35":"H\u00fanagro"}
	langs = {
		'1':{'code': 'ES', 'name': 'Español'}
		,'2':{'code': 'EN', 'name': 'Inglés'}
		,'3':{'code': 'PT', 'name': 'Portugués'}
		,'4':{'code': 'DE', 'name': 'Alemán'}
		,'5':{'code': 'FR', 'name': 'Francés'}
		
		,'29':{'code': 'IR', 'name': 'Iraní'}
		}

	langs_codes = {
		'': 'EN'
		,'Inglés': 'EN'
		,'Español': 'ES'
		,'Portugues': 'PT'
		,'Alemán': 'DE'
		,'Francés': 'FR'
		
		,'Iraní': 'IR'
		}


	def peliculas(self):
		url = "http://www.cuevana.tv/web/peliculas?&hd"
		url = "http://www.cuevana.tv/#!/peliculas/4297/an-unfinished-life"
		url = "http://www.cuevana.tv/#!/peliculas/4297"

		salida = self._mcData.get( url )
		#print salida


	def pel(self):

		url = "http://www.cuevana.tv/player/sources?id=4310&tipo=pelicula"
		url = "http://www.cuevana.tv/web/peliculas?&4310&flypaper"
		url = "player/play?id=4310&tipo=pelicula&def="


		url = "http://www.cuevana.tv/player/source_get"

		"""
		var sources = {"720":{"2":["megaupload","glumbo"]},"360":{"2":["megaupload","glumbo","wupload"]}}, sel_source = 0;
		var label = {
			'360': 'SD (360p)',
			'480': 'SD (480p)',
			'720': 'HD (720p)',
			'1080': 'HD (1080p)'
		};
		var labeli = {"1":"Espa\u00f1ol","2":"Ingl\u00e9s","3":"Portugu\u00e9s","4":"Alem\u00e1n","5":"Franc\u00e9s","6":"Coreano","7":"Italiano","8":"Tailand\u00e9s","9":"Ruso","10":"Mongol","11":"Polaco","12":"Esloveno","13":"Sueco","14":"Griego","15":"Canton\u00e9s","16":"Japon\u00e9s","17":"Dan\u00e9s","18":"Neerland\u00e9s","19":"Hebreo","20":"Serbio","21":"\u00c1rabe","22":"Hindi","23":"Noruego","24":"Turco","26":"Mandar\u00edn","27":"Nepal\u00e9s","28":"Rumano","29":"Iran\u00ed","30":"Est\u00f3n","31":"Bosnio","32":"Checo","33":"Croata","34":"Fin\u00e9s","35":"H\u00fanagro"};
		var labelh = {
			'megaupload': 'Megaupload',
			'glumbo': 'Glumbo',
			'filepost': 'Filepost',
			'wupload': 'Wupload'
		};
		"""
		data = {'def': '720',
			'audio': '2',
			'host': 'megaupload',
			'id': '4310',
			'tipo': 'pelicula'
			}

		post = urllib.urlencode(data)

		salida = self._mcData.post(url, post)
		#salida = self._mcData.get( url )
		#print salida


	@staticmethod
	def featured():

		o = cuevanaMovie()

		url = "http://www.cuevana.tv/web/inicio"

		salida = o._mcData.get( url )

		search1 = '$("#peliculas_row").rowbox('
		pos = salida.find(search1)
		salida2 = salida[pos + len(search1) + 2 :]

		search2 = '$("#episodios_row").rowbox('
		pos = salida2.find(search2)

		finish = ",set:['tit','ano','reparto','director','genero','idioma','duracion']}"
		peliculas = '{"lista"' + salida2[:pos-3-len(finish)] + "}"

		#peliculas = open('info.txt').read()
		#print peliculas
		import json
		peliculas = unicode(peliculas, 'latin-1')
		peliculas = json.loads(peliculas)
		
		result = []
		#for pel in peliculas['lista']['destacado']:
		for pel in peliculas['lista']['estreno']:			

			"""
			o = mcMovie()
			o.id = unicode(pel['id']).encode("utf-8")
			o.title = unicode(pel['tit']).encode("utf-8")
			"""
			o = cuevanaMovie( unicode(pel['id']).encode("utf-8") )
			result.append(o)

		return result



	"""
	def _loadFromUrl(self, url):

		self.url = url

		salida = noootvData.get( url )

		m = re.search('content">[^<]*<div id="post-([0-9]*)', salida)
		if m != None:
			self.id = m.group(1).strip()

		m = re.search('content">[^<]*<div id="post-[0-9]*"[^<]*<h1>([^<]*)', salida)
		if m != None:
			self.titulo = m.group(1).strip()

		m = re.search('dropCap">([^<]*)</span>([^<]*)', salida)
		if m != None:
			self.descripcion = m.group(1).strip() + m.group(2).strip()

		m = re.search('rxposter" src="([^"]*)', salida)
		if m != None:
			self.imagen = m.group(1).strip()

		return

	"""

class cuevanaSerie(mcMovie):

	def __init__ (self, id=None):
		mcMovie.__init__(self, "cuevana_serie", id)


	def loadInfo(self):

		#Serie info
		self.url = "http://www.cuevana.tv/web/series?&" + self.id + "&"
		salida = self._mcData.get( self.url )
		salida = salida.replace('\n', ' ')
		#print salida

		#Cover
		rec_cover_url = re.compile('"img"><img src="([^"]*)')
		match = re.search(rec_cover_url, salida )
		if match != None:
			self.cover_url = match.group(1)

		#Title
		rec_title = re.compile('"tit">([^<]*)')
		match = re.search(rec_title, salida )
		if match != None:
			self.title = unicode(match.group(1).strip(), 'utf-8')


		#Original Title
		rec_original_title = re.compile('tulo original</h2>([^<]*)')
		match = re.search(rec_original_title, salida )
		if match != None:
			self.original_title = unicode(match.group(1).strip(), 'utf-8')


		#Idiomas
		rec_lang = re.compile('<b>Idioma:</b>([^<]*)')
		match = re.search(rec_lang, salida )
		if match != None:
			langs = []
			langs.append( self._getCodeFromName( match.group(1).strip() ) )

			self.languages = langs


		#Idiomas
		rec_sublang = re.compile('tulos:</b>([^<]*)')
		match = re.search(rec_sublang, salida )
		if match != None:
			langs = []
			langs.append( self._getCodeFromName( match.group(1).strip() ) )

			self.sub_languages = langs

		self.url = "http://www.cuevana.tv/#!/peliculas/"+ self.id +"/"

		#Parent Call
		mcMovie.loadInfo(self)


	def loadSources(self):

		url = "http://www.cuevana.tv/player/sources?id="+self.id+"&tipo=pelicula"
		salida = self._mcData.get( url )
		#salida = salida.replace('\n', ' ')
		#print salida

		str1 = "var sources ="
		pos = salida.find(str1)
		pos2 = salida.find("var label =")

		strjson = salida[pos+len(str1):pos2-len(", sel_source = 0; ")]
		result = json.loads(strjson)
		#print result
		for definition in result:
			for lang in result[definition]:
				for server in result[definition][lang]:
					s = mcSource()
					s.service = self.service
					s.id = self.id
					s.server = server
					s.definition = definition
					if int(definition) >= 720:
						s.is_hd = True
					
					s.audio_lang_id = lang
					s.audio_lang = self._getAudioLangFromId(lang)

					self._loadSourceUrl(s)
					self.sources.append(s)

		#Parent Call
		mcMovie.loadSources(self)


	def _loadSourceUrl(self, source):

		url = "http://www.cuevana.tv/player/source_get"

		data = {'def': source.definition,
			'audio': source.audio_lang_id,
			'host': source.server,
			'id': self.id,
			'tipo': 'pelicula'
			}

		post = urllib.urlencode(data)

		salida = self._mcData.post(url, post)
		salida = salida.strip().replace('\xef\xbb\xbf', '')

		if source.server == 'megaupload':
			pos = salida.find('&id='+ self.id)
			salida = salida[:pos]

		if source.server == 'wupload':
			pos = salida.find('?id='+ self.id)
			salida = salida[:pos]

		source.url = salida

	def _getAudioLangFromId(self, id):
		
		l = self.langs[str(id)]		
		return l['code']
	
	def _getCodeFromName(self, name):
		
		return self.langs_codes[str(name)]
		
	
	#{"1":"Espa\u00f1ol","2":"Ingl\u00e9s","3":"Portugu\u00e9s","4":"Alem\u00e1n","5":"Franc\u00e9s","6":"Coreano","7":"Italiano","8":"Tailand\u00e9s","9":"Ruso","10":"Mongol","11":"Polaco","12":"Esloveno","13":"Sueco","14":"Griego","15":"Canton\u00e9s","16":"Japon\u00e9s","17":"Dan\u00e9s","18":"Neerland\u00e9s","19":"Hebreo","20":"Serbio","21":"\u00c1rabe","22":"Hindi","23":"Noruego","24":"Turco","26":"Mandar\u00edn","27":"Nepal\u00e9s","28":"Rumano","29":"Iran\u00ed","30":"Est\u00f3n","31":"Bosnio","32":"Checo","33":"Croata","34":"Fin\u00e9s","35":"H\u00fanagro"}
	langs = {
		'1':{'code': 'ES', 'name': 'Español'}
		,'2':{'code': 'EN', 'name': 'Inglés'}
		,'3':{'code': 'PT', 'name': 'Portugués'}
		,'4':{'code': 'DE', 'name': 'Alemán'}
		,'5':{'code': 'FR', 'name': 'Francés'}
		
		,'29':{'code': 'IR', 'name': 'Iraní'}
		}

	langs_codes = {
		'': 'EN'
		,'Inglés': 'EN'
		,'Español': 'ES'
		,'Portugues': 'PT'
		,'Aleman': 'DE'
		,'Frances': 'FR'
		
		,'Iraní': 'IR'
		}


	def peliculas(self):
		url = "http://www.cuevana.tv/web/peliculas?&hd"
		url = "http://www.cuevana.tv/#!/peliculas/4297/an-unfinished-life"
		url = "http://www.cuevana.tv/#!/peliculas/4297"

		salida = self._mcData.get( url )
		#print salida


	def pel(self):

		url = "http://www.cuevana.tv/player/sources?id=4310&tipo=pelicula"
		url = "http://www.cuevana.tv/web/peliculas?&4310&flypaper"
		url = "player/play?id=4310&tipo=pelicula&def="


		url = "http://www.cuevana.tv/player/source_get"

		"""
		var sources = {"720":{"2":["megaupload","glumbo"]},"360":{"2":["megaupload","glumbo","wupload"]}}, sel_source = 0;
		var label = {
			'360': 'SD (360p)',
			'480': 'SD (480p)',
			'720': 'HD (720p)',
			'1080': 'HD (1080p)'
		};
		var labeli = {"1":"Espa\u00f1ol","2":"Ingl\u00e9s","3":"Portugu\u00e9s","4":"Alem\u00e1n","5":"Franc\u00e9s","6":"Coreano","7":"Italiano","8":"Tailand\u00e9s","9":"Ruso","10":"Mongol","11":"Polaco","12":"Esloveno","13":"Sueco","14":"Griego","15":"Canton\u00e9s","16":"Japon\u00e9s","17":"Dan\u00e9s","18":"Neerland\u00e9s","19":"Hebreo","20":"Serbio","21":"\u00c1rabe","22":"Hindi","23":"Noruego","24":"Turco","26":"Mandar\u00edn","27":"Nepal\u00e9s","28":"Rumano","29":"Iran\u00ed","30":"Est\u00f3n","31":"Bosnio","32":"Checo","33":"Croata","34":"Fin\u00e9s","35":"H\u00fanagro"};
		var labelh = {
			'megaupload': 'Megaupload',
			'glumbo': 'Glumbo',
			'filepost': 'Filepost',
			'wupload': 'Wupload'
		};
		"""
		data = {'def': '720',
			'audio': '2',
			'host': 'megaupload',
			'id': '4310',
			'tipo': 'pelicula'
			}

		post = urllib.urlencode(data)

		salida = self._mcData.post(url, post)
		#salida = self._mcData.get( url )
		#print salida


	@staticmethod
	def featured():

		o = cuevanaMovie()

		url = "http://www.cuevana.tv/web/inicio"

		salida = o._mcData.get( url )

		search1 = '$("#peliculas_row").rowbox('
		pos = salida.find(search1)
		salida2 = salida[pos + len(search1) + 2 :]

		search2 = '$("#episodios_row").rowbox('
		pos = salida2.find(search2)

		finish = ",set:['tit','ano','reparto','director','genero','idioma','duracion']}"
		peliculas = '{"lista"' + salida2[:pos-3-len(finish)] + "}"

		#peliculas = open('info.txt').read()
		#print peliculas
		import json
		peliculas = unicode(peliculas, 'latin-1')
		peliculas = json.loads(peliculas)
		
		result = []
		#for pel in peliculas['lista']['destacado']:
		for pel in peliculas['lista']['estreno']:			

			"""
			o = mcMovie()
			o.id = unicode(pel['id']).encode("utf-8")
			o.title = unicode(pel['tit']).encode("utf-8")
			"""
			o = cuevanaMovie( unicode(pel['id']).encode("utf-8") )
			result.append(o)

		return result



	"""
	def _loadFromUrl(self, url):

		self.url = url

		salida = noootvData.get( url )

		m = re.search('content">[^<]*<div id="post-([0-9]*)', salida)
		if m != None:
			self.id = m.group(1).strip()

		m = re.search('content">[^<]*<div id="post-[0-9]*"[^<]*<h1>([^<]*)', salida)
		if m != None:
			self.titulo = m.group(1).strip()

		m = re.search('dropCap">([^<]*)</span>([^<]*)', salida)
		if m != None:
			self.descripcion = m.group(1).strip() + m.group(2).strip()

		m = re.search('rxposter" src="([^"]*)', salida)
		if m != None:
			self.imagen = m.group(1).strip()

		return

	"""

